local filesystem = {}

function filesystem.base(p)
	-- foo/bar -> foo
	-- foo/bar/ -> foo
	-- foo -> ERROR
	for i=#p,1 do
		
	end
end


-- TODO: This needs to be adapted based on OS

local function resolve_root(root)
	if root == "app" then
		local path = "APPDATA\\bonk\\" -- TODO: Get AppData path (via the system module for example)

		return path
	elseif root == '.' then
		return ".\\"
	end

	error("Invalid path: invalid root: " .. root)
end

function filesystem.to_native(str, default_root)
	local start = 1
	local prevch = 32 -- ' '

	local start, pos, len = 1, 1, #str
	--local type -- Do we need type at all? Should pass in requirements to this function instead

	local first = true
	local path = default_root
	if not path then
		-- Default default..
		path = ".\\"
	end

	while pos <= len do
		local ch = string.byte(str, pos)
		
		if ch == 58 then -- ':'
			if not first then
				error("Invalid path: unexpected colon")
				--return nil
			end

			path = resolve_root(string.sub(str, start, pos - 1))
			start = pos + 1
			first = false
		elseif ch == 47 then -- '/'
			
			if pos - 1 ~= start then
				path = path .. string.sub(str, start, pos - 1) .. '\\'
			end
			start = pos + 1
			first = false
		elseif ch == 46 and prevch == 46 then
			error("Invalid path: .. not allowed")
		end

		pos = pos + 1

		prevch = ch
	end

	if pos - 1 ~= start then
		path = path .. string.sub(str, start, pos - 1)
	end

	return path
end

function filesystem.join(a, b)
	local chop = 0
	while string.sub(b, 1, 3) == "../" do
		b = string.sub(b, 4)
		chop = chop + 1
	end

	while chop > 0 do
		chop = chop - 1
		a = base(a)
	end

	if string.byte(a, i) then
	end
end

--[[ TODO
local old_open_file_r = filesystem.open_file_r
function filesystem.open_file_r(path)
	return old_open_file_r(filesystem.to_native(path))
end

local old_open_file_w = filesystem.open_file_w
function filesystem.open_file_w(path)
	return old_open_file_w(filesystem.to_native(path))
end
]]

return filesystem